package com.yonyou.pmclouds.reason.processor;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.BuziExCodeConst;
import com.yonyou.pmclouds.reason.entity.ProblemReasonVO;
import com.yonyou.pmclouds.reason.mapper.ProblemReasonMapper;
import org.apache.commons.lang3.StringUtils;

public class ProblemReasonUpNameAndCodeCheck implements SingleProcessor<ProblemReasonVO> {
    private ProblemReasonMapper mapper;

    public ProblemReasonUpNameAndCodeCheck(ProblemReasonMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void process(ProblemReasonVO vo, ProblemReasonVO orig) throws BusinessException {
        if (StringUtils.equals(vo.getSname(), orig.getSname()) && StringUtils.equals(vo.getScode(),orig.getScode())) {
            return;
        }

        boolean codeUnique = mapper.countCode(vo.getPkTenant(), vo.getScode(), vo.getCategory()) == 0;
        boolean nameUnique = mapper.countName(vo.getPkTenant(), vo.getSname(), vo.getCategory()) == 0;
        if (StringUtils.equals(vo.getSname(), orig.getSname())) {
            //只校验编码
            if (!codeUnique) {
                throw new BusinessException("已经存在相同的问题原因编码，请修改!", BuziExCodeConst.CODE_CODE_DUPLICATE);
            }
        }

        if (StringUtils.equals(vo.getScode(), orig.getScode())) {
            //只校验名字
            if (!nameUnique) {
                throw new BusinessException("已经存在相同的问题原因名称，请修改!", BuziExCodeConst.CODE_NAME_DUPLICATE);
            }

        }

        if (!codeUnique && !nameUnique) {
            throw new BusinessException("已经存在相同的问题原因编码、名称，请修改!", BuziExCodeConst.CODE_NAME_CODE_DUPLICATE);
        }


    }
}
